package com.aacar.op.web.coupon;

import com.aacar.op.entity.coupon.Coupon;
import com.aacar.op.entity.washer.Washer;
import com.aacar.op.service.coupon.CouponService;
import com.aacar.op.utils.Constant;
import com.aacar.op.utils.DateUtil;
import com.aacar.op.utils.enumeration.MenuPermissions;
import com.aacar.op.utils.pojo.ActionResult;
import com.aacar.op.utils.pojo.datatables.DataTablesResult;
import com.aacar.op.utils.web.PageUtils;
import com.aacar.op.utils.web.Servlets;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 优惠券管理
 * @author Chao
 *
 */
@Controller
@RequestMapping("/op/coupon")
public class CouponController {
	
    private static Logger logger = LoggerFactory.getLogger(CouponController.class);

    @Autowired
    protected CouponService couponService;

    @RequestMapping(method = {RequestMethod.GET})
    public String list(@ModelAttribute("entity") Coupon entity, Model model) {
        return "op/coupon/coupon";
    }

    /**
     *
     *验证batchName是否存在
     * @return JSON true || false
     */
    @RequestMapping(value = "validate_batchname", method = {RequestMethod.GET, RequestMethod.POST})
    public
    @ResponseBody
    Boolean validateBatchName(@RequestParam(value = "batchName", required = true) String batchName) {
        return couponService.validateBatchName(batchName);
    }

    /**
     * 获取batchNameList
     *
     */
    @RequestMapping(value = "get_batchname_list", method = {RequestMethod.POST})
    public
    @ResponseBody
    Object getBatchNameList(Object obj) {
        return couponService.findGroupByBatchName(null);
    }

    /**
     * datatables json
     */
    @RequestMapping(value = "datatables", method = {RequestMethod.GET, RequestMethod.POST})
    public
    @ResponseBody
    DataTablesResult<Washer> datatables(HttpServletRequest request,
                                      @RequestParam(value = "search_startDate", required = false)
                                      @DateTimeFormat(pattern = Constant.DATE_PATTERN_SHORT) Date startDate,
                                      @RequestParam(value = "search_endDate", required = false)
                                      @DateTimeFormat(pattern = Constant.DATE_PATTERN_SHORT) Date endDate) {

        Pageable pageable = PageUtils.pageableFromDateTables(request);
        //使用Map传参到Service层,便于扩展.
        //获取"search_"的参数传as Map.
        Map<String, Object> params = Servlets.getParametersStartingWith(request, "search_");
        logger.info("################# params"+params);
        PageInfo<Coupon> pageInfo = couponService.getPage(params, pageable);
        return DataTablesResult.build(pageInfo);
    }

    /**
     * 编辑页面:: GET
     */
    @RequestMapping(value = "input", method = RequestMethod.GET)
    public String input(@ModelAttribute("entity") Coupon entity, Model model) {
        return "op/coupon/coupon-input";
    }

    /**
     * insert :: POST 生成优惠券
     */
    @RequestMapping(value = "insert", method = RequestMethod.POST)
    public
    @ResponseBody
    ActionResult insert(@Valid @ModelAttribute("entity") Coupon entity, BindingResult result) {

        if (result.hasErrors()) {
            logger.warn(result.toString());
            return ActionResult.failure("数据不合法,保存失败。");
        }

        ActionResult actionResult;
        try {
            couponService.saveBatchCoupon(entity);
            actionResult = ActionResult.success("&quot;保存成功");
        } catch (Exception e) {
            logger.error("用户保存异常:{}", e);
            actionResult = ActionResult.failure("&quot;保存失败。");
        }
        return actionResult;
    }

    private String charSetString(String str){
//        try {
//            return new String(str.getBytes("ISO-8859-1"),"GB2312");
//        }catch (Exception e){
//
//        }
        return str;
    }

    /**
     * export :: POST
     */
    @RequestMapping(value = "export", method = RequestMethod.POST)
    @ResponseBody
    public
    void export(@Valid @ModelAttribute("entity") Coupon entity, HttpServletResponse response) throws Exception {

        List<Coupon> couponList = couponService.findCoupons(entity);
        HSSFWorkbook wb = null;
        wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet(charSetString("优惠券"));
        HSSFRow row;
        HSSFCell cell;
        row = sheet.createRow(0);//创建表格行
        cell = row.createCell(0);
        cell.setCellValue(String.valueOf(charSetString("批次名称")));
        cell = row.createCell(1);
        cell.setCellValue(String.valueOf(charSetString("优惠券号")));
        cell = row.createCell(2);
        cell.setCellValue(String.valueOf(charSetString("优惠券密码")));
        cell = row.createCell(3);
        cell.setCellValue(String.valueOf(charSetString("优惠券金额")));
        cell = row.createCell(4);
        cell.setCellValue(String.valueOf(charSetString("生成时间")));
        cell = row.createCell(5);
        cell.setCellValue(String.valueOf(charSetString("优惠券状态")));
        if (couponList != null) {
            for (int i = 0; i < couponList.size(); i++) {
                Coupon coupon = couponList.get(i);
                row = sheet.createRow(i + 1);//创建表格行
                cell = row.createCell(0);
                cell.setCellValue(coupon.getBatchName());
                cell = row.createCell(1);
                cell.setCellValue(coupon.getCouponNo());
                cell = row.createCell(2);
                cell.setCellValue(coupon.getCouponPwd());
                cell = row.createCell(3);
                cell.setCellValue(coupon.getCouponAmount());
                cell = row.createCell(4);
                cell.setCellValue(DateUtil.date2Str(DateUtil.defaultPattern2, coupon.getCreateTime()));
                cell = row.createCell(5);
                String statusName = "";
                if ("1".equals(coupon.getCouponStatus())) {
                    statusName = charSetString("待使用");
                } else if ("2".equals(coupon.getCouponStatus())) {
                    statusName = charSetString("已使用");
                }
                cell.setCellValue(statusName);
            }
        }
        response.reset();
        // 指定下载的文件名
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssms");
        String dateStr = sdf.format(new Date());
        response.setHeader("Content-Disposition", "attachment;filename="+dateStr+".xls");
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        OutputStream output;
        try {
            output = response.getOutputStream();

            BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);
            bufferedOutPut.flush();
            wb.write(bufferedOutPut);
            bufferedOutPut.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
